<template>
  <div>
    <div class="head" ref="head">
      <div>
        收藏标签
        <div @click="addVisible = true">
          <el-icon> <Plus /> </el-icon>添加标签
        </div>
      </div>
      <div class="tag-list">
        <div :class="{ 'active-tag': !params.labelId }" @click="changetag('')">全部</div>
        <div
          v-for="item in tagList"
          :class="{ 'active-tag': params.labelId == item.labelId }"
          :key="item.labelId"
          @click="changetag(item.labelId)"
        >
          {{ item.labelName }}
          <el-icon @click.stop="openDel(item)">
            <Close />
          </el-icon>
        </div>
      </div>
    </div>
    <el-scrollbar class="goods-list" :height="`calc(100vh - ${height}px - 174px)`">
      <el-empty v-if="!data.length" />
      <div class="container" :style="{ '--num': Math.round(width / 280) }">
        <div class="goods" ref="goods" v-for="item in data">
          <div :class="{ obscure: editing.collectId == item.collectId }">
            <div class="img"><img :src="item.mainPicUrl" alt="" /></div>
            <div class="info">
              <div class="name">{{ item.productName }}</div>
              <div class="price">￥{{ item.businessLowestPrice }}</div>
              <div class="info-tags" ref="tags">
                <div class="info-tags-container">
                  <div v-for="tag in item.labelList ? item.labelList.slice(0, 2) : []">
                    {{ tag.labelName }}
                    <el-icon @click.stop="delGoodsTagItem(item, tag)">
                      <Close />
                    </el-icon>
                  </div>
                  <div class="more" v-if="item.labelList?.length > 2">...</div>
                </div>
              </div>
              <div class="btn" @click="editing = item">设置收藏标签</div>
            </div>
          </div>
          <div class="add-tag-box" v-if="editing.collectId == item.collectId">
            <div class="title">
              设置标签
              <el-icon @click="editing = {}">
                <CaretBottom />
              </el-icon>
            </div>
            <div class="add-tags">
              <div v-for="tag in item.labelList" :key="tag.labelId">
                {{ tag.labelName }}
                <el-icon @click.stop="delGoodsTagItem(item, tag)">
                  <Close />
                </el-icon>
              </div>
              <el-dropdown ref="dropdown" max-height="100px" style="outline: none" v-for="() in addSelectList">
                <div class="select">
                  待选择
                  <el-icon>
                    <arrow-down />
                  </el-icon>
                </div>
                <template #dropdown>
                  <div
                    class="option"
                    style="width: 80px"
                    @click="addGoodsTagItem(item, option)"
                    v-for="option in filterTag"
                    :key="item.labelId"
                  >
                    {{ option.labelName }}
                  </div>
                </template>
              </el-dropdown>
              <div @click="addSelectList += 1">
                <el-icon> <Plus /> </el-icon>添加标签
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pagination" v-if="data.length">
        <div>共{{ total }}条</div>
        <el-dropdown ref="dropdown">
          <div class="select">
            {{ params.size }}
            <el-icon>
              <arrow-down />
            </el-icon>
          </div>
          <template #dropdown>
            <div
              :class="{ option: true, 'active-page': params.size == item }"
              v-for="item in [10, 20, 50, 100]"
              :key="item"
              @click="closeDropdown(item)"
            >
              {{ item }}
            </div>
          </template>
        </el-dropdown>
        <div :class="{ change: true, disable: params.page == 1 }" @click="upPage">上一页</div>
        <div :class="{ 'page-num': true, 'page-num-current': item == params.page }" v-for="item in pageNum">
          {{ item }}
        </div>
        <div :class="{ change: true, disable: params.page == pageNum }" @click="nextPage">下一页</div>
        <div>到 <input type="text" v-model.number="pageIndex" @keyup.enter="toPage" />页</div>
      </div>
    </el-scrollbar>
    <el-dialog v-model="addVisible" modal-class="add-modal" width="420" :show-close="false" align-center @closed="label = {}">
      <template #title>
        <span>新增收藏标签</span>
      </template>
      <div class="name">
        <input type="text" v-model="label.labelName" @change="verifyLabelName" @blur="verifyLabelName" />
        <span>{{ label.labelNameErr }}</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="close" @click="addVisible = false">取消</div>
          <div class="confirm" type="primary" @click="addTagConfirm">确定</div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="delVisible" modal-class="add-modal" width="420" :show-close="false" align-center>
      <div class="del-name">
        {{ delParams.labelName }}
      </div>
      <div class="del-tip">删除标签后，在标签内收藏的商品也将被移除，确认要删除该标签 ！</div>
      <template #footer>
        <div class="dialog-footer">
          <div class="close" @click="delVisible = false">取消</div>
          <div class="confirm" type="primary" @click="delTagConfirm">确定</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getTagList, getGoodsList, addTag, delTag, delGoodsTag, addGoodsTag } from "@/apis/manage/collection";
import { ref, onMounted, computed } from "vue";
import { useElementSize } from "@vueuse/core";
import { ElMessage } from "element-plus";
import useManageStore from "@/store/modules/manage";

const manageStore = useManageStore();
const head = ref(null);
const { height, width } = useElementSize(head);

const editing = ref({});
const addVisible = ref(false);
const delVisible = ref(false);
const label = ref({
  labelName: "",
  labelNameErr: ""
});
const delParams = ref({});
const addSelectList = ref(0);

/**
 * 自定义分页
 */
const pageNum = computed(() => {
  const num = Math.ceil(total.value / params.value.size);
  return num ? num : 1;
});
const upPage = () => {
  if (params.value.page == 1) return;
  params.value.page -= 1;
  init();
};
const nextPage = () => {
  if (params.value.page == pageNum.value) return;
  params.value.page += 1;
  init();
};
const tagList = ref([]);
const params = ref({
  size: 10,
  page: 1
});
const filterTag = computed(() => {
  const haveIds = editing.value.labelList ? editing.value.labelList.map(v => v.labelId) : [];
  return tagList.value.filter(v => !haveIds.includes(v.labelId));
});
const getTags = (list = []) => {
  if (list?.length == 3 || list?.length < 3) return list;
  else {
    console.log(list?.slice(0, 2));
    return list?.slice(0, 2);
  }
};
const pageIndex = ref(params.value.page);
const total = ref(0);
const data = ref([]);
const dropdown = ref(null);

const getTagListData = async () => {
  const res = await getTagList();
  tagList.value = res.data;
};
const getGoods = async () => {
  const res = await getGoodsList(params.value);
  data.value = res.data.records;
  total.value = res.data.total;
  manageStore.collectionTotal = res.data.total;
};
const verifyLabelName = () => {
  if (!label.value.labelName || !label.value.labelName.trim()) {
    label.value.labelNameErr = "标签名称不能为空";
    return false;
  } else if (label.value.labelName.length > 8) {
    label.value.labelNameErr = "标签名称不能超过8个字符";
    return false;
  }
  label.value.labelNameErr = "";
  return true;
};
const addTagConfirm = async () => {
  if (verifyLabelName()) {
    await addTag(label.value.labelName);
    getGoods();
    addVisible.value = false;
    label.value = {};
    getTagListData();
    ElMessage("新增收藏标签成功");
  }
};
const delTagConfirm = async () => {
  await delTag(delParams.value.labelId);
  getTagListData();
  delVisible.value = false;
  label.value.labelName = "";
  ElMessage("删除收藏标签成功");
};
const init = async () => {
  getTagListData();
  getGoods();
};
const delGoodsTagItem = async (item, tag) => {
  await delGoodsTag({
    collectProductId: item.collectProductId,
    labelId: tag.labelId
  });
  getGoods();
};
const addGoodsTagItem = async (item, tag) => {
  await addGoodsTag({
    collectProductId: item.collectProductId,
    labelId: tag.labelId
  });
  addSelectList.value -= 1;
  getGoods();
};
const changetag = id => {
  params.value.labelId = id;
  getGoods();
};
const openDel = item => {
  delParams.value = item;
  delVisible.value = true;
};
const toPage = () => {
  pageIndex.value = pageIndex.value < 1 ? 1 : pageIndex.value;
  pageIndex.value = pageNum.value < pageIndex.value ? pageNum.value : pageIndex.value;
  params.value.page = pageIndex.value;
  getGoods();
};
const closeDropdown = item => {
  dropdown.value.handleClose();
  const t = setTimeout(() => {
    params.value.size = item;
    getGoods();
    params.value.page = 1;
    clearTimeout(t);
  }, 200);
};
onMounted(() => {
  init();
});
</script>

<style lang="scss" scoped>
.head {
  width: 100%;
  background: white;
  box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
  border-radius: 10px;
  margin-bottom: 20px;

  > div:first-child {
    border-bottom: 1px solid #e1e6ed;
    display: flex;
    height: 60px;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    font-size: 16px;
    font-weight: bold;
    color: #3d3d3d;

    div {
      background: #424e66;
      padding: 0 20px;
      height: 32px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;

      .el-icon {
        color: white;
      }
    }
  }

  .tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 20px;

    > div {
      padding: 6px 12px;
      border-radius: 4px;
      font-size: 12px;
      box-shadow: 0px 3px 8px 0px rgba(85, 84, 84, 0.2);
      display: flex;
      align-items: center;
      gap: 4px;
      user-select: none;
    }

    .active-tag {
      background: #041830;
      color: white;
    }
  }
}

.goods-list {
  @mixin box {
    box-shadow: 0px 3px 8px 0px rgba(4, 19, 74, 0.04);
    border-radius: 4px;
  }

  .container {
    display: grid;
    margin-bottom: 20px;
    grid-template-columns: repeat(var(--num), 1fr);
    gap: 20px;

    .obscure {
      filter: blur(2px);
    }

    .goods {
      flex: 1;
      background: #ffffff;
      box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
      border-radius: 10px;
      position: relative;
      overflow: hidden;

      .add-tag-box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 2;
        background: rgba(0, 0, 0, 0.5);
        padding: 10px;
        box-sizing: border-box;

        .title {
          color: white;
          font-weight: bold;
          display: flex;
          justify-content: space-between;
        }

        .add-tags {
          display: flex;
          margin-top: 8px;
          gap: 16px;
          flex-wrap: wrap;

          div {
            padding: 0 10px;
            height: 24px;
            background: #f2f3f5;
            border-radius: 4px 4px 4px 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            user-select: none;
            font-size: 10px;
            gap: 4px;
            outline: none;
          }
        }
      }

      .img {
        width: 100%;
        height: 200px;
        border-radius: 10px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }

      .info {
        padding: 10px;
        text-align: center;

        .name {
          font-size: 16px;
          color: #3d3d3d;
          font-weight: bold;
          margin-bottom: 8px;
        }

        .price {
          margin-bottom: 20px;
        }

        .size {
          text-align: left;
          display: flex;
          justify-content: space-between;
          margin-bottom: 16px;
          font-size: 12px;
          color: #86909c;
        }

        .btn {
          width: 100%;
          height: 24px;
          background: #4e5969;
          border-radius: 4px;
          color: white;
          line-height: 24px;
          user-select: none;
        }

        .info-tags {
          height: 24px;
          position: relative;
          margin-bottom: 20px;

          .info-tags-container {
            width: auto;
            gap: 10px;
            display: flex;
            height: 24px;
            width: 100%;
            overflow: hidden;
            position: absolute;
            flex-wrap: wrap;

            > div {
              flex: 1;
              height: 24px;
              background: #f2f3f5;
              border-radius: 4px;
              color: #86909c;
              font-size: 10px;
              gap: 4px;
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 0 10px;
              white-space: nowrap;
            }

            .more {
              width: 34px;
              max-width: 34px;
              height: 24px;
              background: #f2f3f5;
              border-radius: 4px;
            }
          }
        }
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;

    .page-num {
      width: 30px;
      height: 30px;
      @include box;
      text-align: center;
      line-height: 30px;
      background: white;
      user-select: none;
    }

    .page-num-current {
      color: white;
      background: #4e5969;
    }

    .change {
      background: white;
      @include box;
      height: 30px;
      padding: 0 10px;
      line-height: 30px;
      text-align: center;
      user-select: none;
    }

    .disable {
      color: #cad0d8;
      cursor: not-allowed;
    }

    input {
      height: 30px;
      background: white;
      @include box;
      width: 30px;
      border: none;
      outline: none;
      padding: 0 10px;
      font-size: 12px;
      text-align: center;
    }

    .select {
      height: 30px;
      padding: 0 10px;
      display: flex;
      align-items: center;
      @include box;
      gap: 10px;
      background: white;
    }
  }
}

.option {
  width: 60px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  user-select: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.active-page {
  color: white;
  background: #4e5969;
}

.add-modal {
  span {
    color: #131414;
    font-size: 18px;
  }

  .name {
    margin: 24px 0 40px;

    input {
      width: 100%;
      height: 32px;
      background: #f2f3f5;
      border-radius: 2px;
      border: none;
      outline: none;
      padding: 0 10px;
      color: #86909c;
      box-sizing: border-box;
    }

    span {
      color: #fc3333;
      font-size: 12px;
    }
  }

  .del-name {
    border: 1px solid #dcdfe6;
    width: 200px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    margin: 0 auto;
  }

  .del-tip {
    text-align: center;
    margin: 20px 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;

  > div {
    user-select: none;
    height: 30px;
    border-radius: 2px;
    padding: 0 24px;
    line-height: 30px;
  }

  .close {
    background: #f2f3f5;
  }

  .confirm {
    background: #041830;
    color: white;
  }
}
</style>
